﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using ElectronStoreDAL;
using System.Drawing;

namespace ElectronStore
{
	public partial class Catalog : System.Web.UI.Page
	{
		private int countItem = 4;
		private int indexPage;
		private int idCategory;

		public const string ShowParametersCommandName = "ShowParameters";

		protected void Page_Load(object sender, EventArgs e)
		{
			ElectronStoreSource dataSource = new ElectronStoreSource();
			List<Category> listCategories = dataSource.GetCategories();

			if (listCategories == null)
				return;
			if (!int.TryParse(Request.Params["id"], out idCategory))
				idCategory = 1;
			if (!int.TryParse(Request.Params["page"], out indexPage))
				indexPage = 1;

			if (!IsPostBack)
			{
				//Fill the list of links to categories
				bool flag = true;
				foreach (Category cat in listCategories)
				{
					if (cat.CategoryID == idCategory)
					{
						Label lbl = new Label();
						lbl.Text = cat.Name;
						lbl.ForeColor = Color.FromArgb(81, 147, 185);
						lbl.Style.Add("margin-left", "10px");
						insertItem.Controls.Add(lbl);
						flag = false;
						continue;
					}

					if (flag)
						blCategories1.Items.Add(new ListItem(cat.Name, String.Format(GeneralResource.urlCatalog, cat.CategoryID)));
					else
						blCategories2.Items.Add(new ListItem(cat.Name, String.Format(GeneralResource.urlCatalog, cat.CategoryID)));
				}
				blCategories1.ForeColor = Color.ForestGreen;
			}

			pager.IdCategory = idCategory;
			pager.CountItem = countItem;
			pager.IndexPage = indexPage;

		}   //protected void Page_Load


		protected void Page_PreRender(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				ElectronStoreSource dataSource = new ElectronStoreSource();
				List<ElectronStoreDAL.Product> listProducts;
				listProducts = dataSource.GetRangeProducts(idCategory, (indexPage - 1) * countItem, countItem);
				lvProducts.DataSource = listProducts;
				DataBind();
			}
		}


		protected void lvProducts_ItemCommand(object sender, ListViewCommandEventArgs e)
		{
			switch (e.CommandName)
			{
				case ShowParametersCommandName:
					{
						int id;
						if (int.TryParse(e.CommandArgument.ToString(), out id))
						{
							string query = string.Format(GeneralResource.urlProduct, id);
							Response.Redirect(query);
						}
					}
					break;
			}
		}

	}
}